package com.kindac.together.db;

import java.util.Date;
import java.util.HashMap;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.kindac.together.R;
import com.kindac.together.common.Kin;

/**
 * sqlite db
 * 
 * @author kindac
 */
public class KinDB {

    private static final int    DATABASE_VERSION      = Kin.dBVer;
    private static final String DATABASE_NAME         = Kin.KinDB;

    // togethers
    private static final String CREATE_TABLE_TOGETHER = "create table if not exists togethers (id integer primary key autoincrement, "
                                                        + "post text, time varchar(50));";
    private static final String TOGETHER_TABLE        = "togethers";
    // configs known1 打开彩蛋1 known2 打开彩蛋2 open 27次还是没有打开任何,我给点提示
    private static final String CREATE_TABLE_CONFIGS  = "create table if not exists configs (id integer primary key autoincrement, "
                                                        + "known0 integer DEFAULT 0 NOT NULL, known1 integer DEFAULT 0 NOT NULL, known2 integer DEFAULT 0 NOT NULL, open integer DEFAULT 0 NOT NULL, post integer DEFAULT -1 NOT NULL);";
    private static final String INSERT_CONFIGS        = "insert into configs (id) values (0)";
    private static final String CONFIGS_TABLE         = "configs";

    private SQLiteDatabase      db;

    private static KinDB        sInstance;

    public KinDB(Context ctx) {
        db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
        // db.execSQL("DROP TABLE IF EXISTS "+ SETTINGS_TABLE);
        // added eula to this class to fix trac #49
        db.execSQL(CREATE_TABLE_TOGETHER);
        db.execSQL(CREATE_TABLE_CONFIGS);

        if (db.getVersion() < 1) {// first
            // user is new install
            db.execSQL(INSERT_CONFIGS);
            String demo = "insert into togethers (post, time) values ('"
                          + ctx.getResources().getString(R.string.text_demo) + "', datetime('now'))";
            db.execSQL(demo);
        }
        if (db.getVersion() < DATABASE_VERSION) {
            // upgrade
            db.setVersion(DATABASE_VERSION);
        }
        db.close();
    }

    // 唯一实例化
    public static KinDB getInstance(Context activity) {
        if (sInstance == null) {
            sInstance = new KinDB(activity);
        }
        return sInstance;
    }

    /** 新增post */
    public boolean addPost(Context ctx, String post) {
        boolean returnValue = false;
        db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
        ContentValues values = new ContentValues();
        values.put("post", post);
        values.put("time", new Date().toLocaleString());
        long id = db.insert(TOGETHER_TABLE, null, values);
        returnValue = id > 0;
        // 保存post 用于下次现实
        if (returnValue) {
            values = new ContentValues();
            values.put("post", id);
            db.update(CONFIGS_TABLE, values, null, null);
        }
        db.close();
        return (returnValue);
    }

    public String getOnePost(Context ctx, int id) {
        db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
        Cursor c = db.query(TOGETHER_TABLE, new String[] { "post" }, "id='" + id + "'", null, null, null, null);
        String post = null;
        if (c.getCount() > 0) {
            c.moveToFirst();
            post = c.getString(0);
        }
        c.close();
        db.close();
        return post;
    }

    /** 获取post all */
    public Cursor getPost(Context ctx) {
        db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
        Cursor c = db.query(TOGETHER_TABLE, new String[] { "id as _id", "post", "time" }, null, null, null, null, null);
        return c;
    }

    /** 更新一条post */
    public boolean updatePost(Context ctx, int id, String post) {
        db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
        ContentValues values = new ContentValues();
        values.put("post", post);
        values.put("time", new Date().toLocaleString());
        boolean returnValue = db.update(TOGETHER_TABLE, values, "id='" + id + "'", null) > 0;
        // 保存post 用于下次现实
        if (returnValue) {
            values = new ContentValues();
            values.put("post", id);
            db.update(CONFIGS_TABLE, values, null, null);
        }
        db.close();
        return (returnValue);
    }

    /** 清空together */
    public void reSetPosts(Context ctx) {
        db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
        db.delete(TOGETHER_TABLE, null, null);
        db.close();
    }

    /** 删除一条 */
    public boolean delPost(Context ctx, String id) {
        db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
        if (id == null || id.equals("")) {
            return false;
        }
        db.delete(TOGETHER_TABLE, "id='" + id + "'", null);
        db.close();
        return true;
    }

    /** 配置表 目前只存用户最后登录时间 */
    public boolean updateConfigs(Context ctx, int known0, int known1, int known2, int open, int post) {
        db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
        ContentValues values = new ContentValues();
        if (known0 != 0) {
            values.put("known0", known0);
        }
        if (known1 != 0) {
            values.put("known1", known1);
        }
        if (known2 != 0) {
            values.put("known2", known2);
        }
        if (open != 0) {
            values.put("open", open);
        }
        if (post != -1) {
            values.put("open", open);
        }
        boolean returnValue = db.update(CONFIGS_TABLE, values, null, null) > 0;
        db.close();
        return (returnValue);
    }

    /**
     * 数据库有错误,重新来
     * 
     * @param ctx
     * @return
     */
    public boolean saveConfig(Context ctx) {
        db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
        ContentValues values = new ContentValues();
        values.put("post", -1);
        boolean returnValue = db.update(CONFIGS_TABLE, values, null, null) > 0;
        db.close();
        return (returnValue);
    }

    /** 查看配置表 */
    public HashMap<String, Integer> getConfig(Context ctx) {
        db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);
        Cursor c = db.query(CONFIGS_TABLE, new String[] { "known0", "known1", "known2", "open", "post" }, null, null,
                            null, null, null, null);
        int known0, known1, known2, open, post;
        HashMap<String, Integer> config = null;
        if (c.getCount() > 0) {
            c.moveToFirst();
            known0 = c.getInt(0);
            known1 = c.getInt(1);
            known2 = c.getInt(2);
            open = c.getInt(3);
            post = c.getInt(4);
            config = new HashMap<String, Integer>();
            config.put("known0", known0);
            config.put("known1", known1);
            config.put("known2", known2);
            config.put("open", open);
            config.put("post", post);
        }
        c.close();
        db.close();
        return config;
    }

}
